﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace _21_JWT.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DemoController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        public DemoController(IConfiguration configuration) { 
            this._configuration = configuration;
        }
        [HttpGet]
        public ActionResult CreateJWT()
        {
            List<Claim> claims = new List<Claim>();
            // 尽量用ClaimTypes.Name
            claims.Add(new Claim("Passport", "123456"));
            claims.Add(new Claim("QQ", "888888"));
            claims.Add(new Claim(ClaimTypes.Name, "aggie"));
            claims.Add(new Claim(ClaimTypes.NameIdentifier, "111111"));

            string key = _configuration["jwtKey"]; 
            // Console.WriteLine(key);
            DateTime expires=DateTime.Now.AddMonths(1);

            byte[] secBytes=Encoding.UTF8.GetBytes(key);
            var secKey = new SymmetricSecurityKey(secBytes);
            var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
            var tokenDescriptor = new JwtSecurityToken(claims: claims, expires: expires, signingCredentials: credentials);
            string jwt=new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);

            return Ok(jwt);

        }
        [HttpPost]
        public ActionResult 校验(string jwt)
        {
            string key = _configuration["jwtKey"];
            JwtSecurityTokenHandler tokenHandler = new();
            TokenValidationParameters valParam = new();
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            valParam.IssuerSigningKey= securityKey;
            valParam.ValidateIssuer = false;
            valParam.ValidateAudience = false;
            ClaimsPrincipal principal = tokenHandler.ValidateToken(jwt, valParam, out SecurityToken secToken);
            foreach (var claim in principal.Claims)
            {
                Console.WriteLine($"{claim.Type}={claim.Value}");
            }
            return Ok();
        }
    }
}
